package com.thank.concurrency.samples.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.*;

/**
 * 演示CyclicBarrier的await方法的timeout参数
 */
@Slf4j
public class CyclicBarrierExample3 {

    // 指定有多少个线程同步等待
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

    public static void main(String[] args) throws Exception {
        ExecutorService exec = Executors.newCachedThreadPool();

        for (int i = 0; i < 10; i++) {
            final int threadNum = i;
            // 延迟1秒, 方便观察
            Thread.sleep(1000);
            exec.execute(() -> {
                try {
                    race(threadNum);
                } catch (Exception e) {
                    log.error("exception", e);
                }
            });
        }

        exec.shutdown();
    }

    private static void race(int threadNum) throws Exception {
        Thread.sleep(1000);
        log.info("{} is ready", threadNum);

        // 每个线程等待2秒, 如果超过, 就不等了, 继续往下
        // 由于超时后状态可能会改变，所以会抛出BarrierException异常，如果想继续往下执行，需要加上try-catch
        try {
            cyclicBarrier.await(2000, TimeUnit.MILLISECONDS);
        } catch (BrokenBarrierException|TimeoutException e) {
            log.warn("oh, it's nothing~");
        }
        log.info("{} is continue", threadNum);
    }
}
